package com.sjz.myfrist;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/***
 *  httputil工具封装类测试
 */
public class HttpUtilActivity extends AppCompatActivity  implements View.OnClickListener{

    TextView responseText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.httputil);
        Button sendRequest = (Button) findViewById(R.id.send_httputil_request);
        responseText = (TextView) findViewById(R.id.response_httputil_text);
        sendRequest.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.send_httputil_request) {
            sendRequestWithOkHttp();
        }
    }
    private void sendRequestWithOkHttp() {
        HttpUtil.sendOkHttpRequest("http://www.baidu.com", new okhttp3.Callback(){
            @Override
            public void onFailure(Call call, IOException e) {
//                这里对异常处理
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
//                这里得到服务器返回的具体内容
                String responseData = response.body().string();
                showResponse(responseData);
            }
        });
    }

    private void showResponse(final String response) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // 在这里进行UI操作，将结果显示到界面上
                responseText.setText(response);
            }
        });
    }


}